package org.ix.net.controllers;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.ix.net.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ix.data.entities.HNode;
import org.ix.data.manager.POJOManager;
import org.ix.data.models.Items;
import org.ix.data.models.Items.Item;
import org.ix.data.models.Types;
import org.ix.data.models.Types.Type;

public class Rela extends BaseLocalServlet {

    public String getServletInfo() {
        return "RELA servlet";
    }

    protected void serve(HttpServletRequest req, HttpServletResponse res) {
        String itemid = req.getParameter("itemid");
        String typeid = req.getParameter("typeid");
        String act = nvc(req.getParameter("act"));

        if (act.equals("additem")) {
            out.println(addItem(req));
        }

        out.println("<p>Items</p>");
        out.println(loadItems(itemid, act));
        out.println("<p>Types</p>");
        out.println(loadTypes(typeid, act));
        out.println("<p>Types (Hierarchical view)</p>");
        out.println(loadHTypes(typeid));

        out.println("</body>");
        out.println("</html>");
    }

    public String addItem(HttpServletRequest req) {
        Connection cnn = (Connection) getServletContext().getAttribute("connection");
        Types typesManager = new Types(cnn);
        Items itemsManager = new Items(cnn);

        StringBuffer sbHTML = new StringBuffer(3000);

        Item item = new Item();
        item = (Item) POJOManager.loadObject(req, item);
        /*String[][] errors = (String[][])req.getAttribute("loaderrors");
        if(errors!=null) {
        sbHTML.append("<pre>").append(errors[0][0]).append("-").append(errors[0][1]).append("</pre>");
        }*/
        Date now = new Date();
        if (item.dtcreate == null) {
            item.dtcreate = new Timestamp(now.getTime());
        }
        if (item.dtupdate == null) {
            item.dtupdate = new Timestamp(now.getTime());
        }

        String ipkid = nvc(req.getParameter("ipkid"));
        String name = req.getParameter("name");
        String val = req.getParameter("val");
        String idescr = req.getParameter("idescr");
        String ifktype = req.getParameter("ifktype");
        if (POJOManager.isComplete(item)) {
            int rows = 0;
            try {
                if(ipkid==null || ipkid.equals("")) {
                    rows = itemsManager.insertItem(item);
                } else {
                    Item itemWhere = new Item();
                    itemWhere.ipkid = Long.valueOf(ipkid);
                    rows = itemsManager.updateItem(item, itemWhere);
                }
            } catch (SQLException ex) {
                Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (rows == 1) {
                sbHTML.append("<p>").append(lbl("rela.addItem")).append(":</p>");
            }
        }
        Type filter = new Type();
        if (ifktype != null) {
            filter.fktype = Long.valueOf(ifktype);
        }
        ArrayList<Type> types = null;
        try {
            types = typesManager.loadTypes(filter);
        } catch (SQLException ex) {
            Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, ex);
        }
        sbHTML.append("<form name=\"frmItem\" method=\"GET\">");
        sbHTML.append("<input type=\"hidden\" name=\"act\" value=\"additem\">").append("<br/>");
        sbHTML.append("<input type=\"hidden\" name=\"ipkid\" value=\"").append(ipkid).append("\">").append("<br/>");
        sbHTML.append("<input type=\"text\" maxlenght=\"255\" name=\"name\" value=\"").append(nvc(name)).append("\">").append("<br/>");
        sbHTML.append("<input type=\"text\" maxlenght=\"255\" name=\"val\" value=\"").append(nvc(val)).append("\">").append("<br/>");
        sbHTML.append("<textarea maxlenght=\"1023\" rows=\"5\" cols=\"80\" name=\"idescr\">").append(nvc(idescr)).append("</textarea>").append("<br/>");
        if (types != null) {
            sbHTML.append("<select name=\"ifktype\">");
            Iterator<Types.Type> iterTypes = types.iterator();
            while (iterTypes.hasNext()) {
                Types.Type type = iterTypes.next();
                sbHTML.append("<option value=\"").append(type.tpkid).append("\">").append(type.tdescr).append("</option>");
            }
            sbHTML.append("</select>");
        }
        sbHTML.append("<input type=\"submit\" name=\"btnSend\" value=\"").append(lbl("rela.btnSend")).append("\">").append("<br/>");
        sbHTML.append("</form>");
        return sbHTML.toString();
    }

    public String loadItems(String itemid, String act) {
        Connection cnn = (Connection) getServletContext().getAttribute("connection");
        Items itemsManager = new Items(cnn);
        StringBuffer sbHTML = new StringBuffer(3000);
        if (itemid != null) {
            Item item = new Item();
            item.ipkid = Long.valueOf(itemid);
            try {
                if (act != null && act.equals("delitem")) {
                    int rows = itemsManager.deleteItems(item);
                    sbHTML.append("<p>Deleted ").append(rows).append(" items");
                } else {
                    item = itemsManager.loadItem(item);
                    if (item != null) {
                        sbHTML.append("<p>Selected item: ").append(item.name).append(", ").append(item.val).append("</p>");
                    }
                }
            } catch (SQLException exc) {
                Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, exc);
            }
        }

        sbHTML.append("<a href=\"./rela?act=additem\">").append("<img src=\"" + prop("appname") + "/static/images/list-add.png\" alt=\"add item\" />").append("</a><br/>");

        sbHTML.append("<ul>");

        ArrayList<Items.Item> items = null;
        try {
            items = itemsManager.loadItems(null);
        } catch (SQLException exc) {
            Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, exc);
            items = new ArrayList<Items.Item>();
        }

        Iterator<Items.Item> iterItems = items.iterator();
        while (iterItems.hasNext()) {
            Items.Item item = iterItems.next();

            sbHTML.append("<li>");
            sbHTML.append("<a href=\"./rela?itemid=").append(item.ipkid).append("\">").append(item.name).append("</a> ").append(item.val);
            sbHTML.append("<br/>");
            sbHTML.append("<a href=\"./rela?act=delitem&itemid=").append(item.ipkid).append("\"><img src=\"" + prop("appname") + "/static/images/list-remove.png\" alt=\"remove\" />").append("</a>");
            sbHTML.append("</li>");
        }

        sbHTML.append("</ul>");
        return sbHTML.toString();
    }

    public String loadTypes(String typeid, String act) {
        Connection cnn = (Connection) getServletContext().getAttribute("connection");
        Types typesManager = new Types(cnn);
        StringBuffer sbHTML = new StringBuffer(3000);
        if (typeid != null) {
            Type type = new Type();
            type.tpkid = Long.valueOf(typeid);

            try {
                if (act != null) {
                    if(act.equals("deltype")) {
                        int rows = typesManager.deleteTypes(type);
                        sbHTML.append("<p>Deleted ").append(rows).append(" types");
                    } else if (act.equals("addchildtype")) {
                        type.tpkid = null;
                        type.fktype = Long.valueOf(typeid);
                        type.tdescr = "new type";
                        int rows = typesManager.insertType(type);
                        sbHTML.append("<p>Insert ").append(rows).append(" types");
                    }
                } else {
                    type = typesManager.loadType(type);
                }
            } catch (SQLException exc) {
                Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, exc);
            }
            if (type != null) {
                sbHTML.append("<p>Selected type: ").append(type.tdescr).append("</p>");
            }
        }

        sbHTML.append("<ul>");

        ArrayList<Types.Type> types = null;
        try {
            types = typesManager.loadTypes(null);
        } catch (SQLException exc) {
            Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, exc);
            types = new ArrayList<Types.Type>();
        }

        Iterator<Types.Type> iterTypes = types.iterator();
        while (iterTypes.hasNext()) {
            Types.Type type = iterTypes.next();

            sbHTML.append("<li>");
            sbHTML.append("<a href=\"./rela?typeid=").append(type.tpkid).append("\">").append(type.tdescr).append(" (").append(type.fktype).append(")").append("</a>");
            sbHTML.append("<br/>");
            sbHTML.append("<a href=\"./rela?act=addchildtype&typeid=").append(type.tpkid).append("\" ><img src=\"" + prop("appname") + "/static/images/list-add.png\" alt=\"add child\" /></a>");
            sbHTML.append("<a href=\"./rela?act=deltype&typeid=").append(type.tpkid).append("\" ><img src=\"" + prop("appname") + "/static/images/list-remove.png\" alt=\"remove\" /></a>");
            sbHTML.append("</li>");
        }

        sbHTML.append("</ul>");
        return sbHTML.toString();
    }

    public String loadHTypes(String typeid) {
        Connection cnn = (Connection) getServletContext().getAttribute("connection");
        Types typesManager = new Types(cnn);
        StringBuffer sbHTML = new StringBuffer(3000);
        if (typeid != null) {
            sbHTML.append("<pre>");
            Type type = new Type();
            type.tpkid = Long.valueOf(typeid);
            HNode node = null;
            try {
                node = typesManager.loadHType(type);
            } catch (SQLException exc) {
                Logger.getLogger(Rela.class.getName()).log(Level.SEVERE, null, exc);
            }
            if (node != null) {
                sbHTML.append(node.toXMLString(true, true));
            }
            sbHTML.append("</pre>");
            /*sbHTML.append("<pre>");
            if (node != null) {
            sbHTML.append(node.toJSONString());
            }
            sbHTML.append("</pre>");*/
        }

        return sbHTML.toString();
    }
}
